import { App } from "vue"
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router"
import Login from "../views/Login/index.vue"
import { useUserStore } from "@/store/user/index"
import { user } from "@/request"
import { ElMessage } from "element-plus"


const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: "Login",
        component: Login
    },

]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

router.beforeEach((to, from, next) => {
    const UserStore = useUserStore()
    let token = localStorage.getItem("token")
    if (!token && to.path !== "/login") {
        ElMessage.warning("请先登录")
        next("/login")
    } else if (token && to.path.toLocaleLowerCase() === "/login") {
        ElMessage.warning("请先退出登录")
        next(from.path)
    } else if (token &&
        UserStore.infoArr.length === 0 &&
        router.getRoutes().length === 1 &&
        (from.path === "/" || from.path === "/login")) {
        console.log(1);

        user.userIofoAPI().then(res => {
            UserStore.infoArr = res.data.menus
            UserStore.name = res.data.username
            UserStore.activeMenus.forEach((parent) => {
                const route: RouteRecordRaw =
                {
                    path: "/" + parent.name,
                    name: parent.name,
                    component: () => import("../views/Home/index.vue"),
                    children: []
                };
                parent.children?.forEach((child) => {
                    route.children.push({
                        path: `/${parent.name}/${child.name}`,
                        name: child.name,
                        component: () => import(`../views/${parent.name}/${child.name}.vue`),
                    })
                })

                router.addRoute(route)
                console.log(1);
            })
            router.addRoute({
                path: '/',
                name: "home",
                redirect: "/index",
                component: () => import("../views/Home/index.vue"),
                children: [
                    {
                        path: "/index",
                        name: "index",
                        component: () => import("../views/index/index.vue")
                    }
                ]
            })
            next(to.path)
        })
    } else {
        console.log(2);

        next()
    }
})

export default (app: App<Element>) => {
    app.use(router)
}
export { router }